package com.example.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 */
public class JwtUtil {

    private static final String SECRET = "wanho";

    /**
     * 生成令牌
     */
    public static String generate(Map<String, Object> payload){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, 6); // 6小时后过期

        String token = JWT.create()
                .withPayload(payload)
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 校验令牌
     */
    public static boolean valid(String token){
        try{
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (RuntimeException e){
            return false;
        }
    }

    /**
     * 解析令牌
     */
    public static Integer parseInteger(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static String parseString(String token, String key){
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asString();
    }


    public static void main(String[] args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NSwidXNlck5hbWUiOiJ0b20iLCJleHAiOjE3NTE2MzIwNjl9.npcQMgSBp73LMhosbrif3Xs_rYdE-EUcTsxk1ATHIoA";

        System.out.println(JwtUtil.parseInteger(token, "id"));
    }

}
